import 'package:flutter/material.dart';
import 'package:nihao_flutter/model/post.dart';


class DataTableDemo extends StatefulWidget {
  @override
  _DataTableDemoState createState() => _DataTableDemoState();
}

class _DataTableDemoState extends State<DataTableDemo> {
  int _sortColumnIndex=0;
  bool _sortAssending = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title:Text('DataTableDemo'),
          elevation: 0.0,
        ),
         body: Container(
         padding: EdgeInsets.all(10),
         child: ListView(
           children: <Widget>[
             DataTable(
               sortColumnIndex: _sortColumnIndex,
               sortAscending: _sortAssending,
              //  onSelectAll: (bool value){
              //    setState(() {
              //      value = true;
              //    });
              //  },
               columns: [
                 DataColumn(
                   label:Container(
                      child: Text('Title'),
                   ),
                   onSort: (int index, bool ascending){
                        setState(() {
                          _sortColumnIndex = index;
                          _sortAssending = ascending;
                        });
                        posts.sort((a,b){
                          if(!ascending){
                            final c = a;
                            a=b;
                            b=c;
                          }
                           return a.title.length.compareTo(b.title.length);
                        });
                   },
                  ),
                  DataColumn(
                   label:Container(
                      child: Text('Author'),
                     // width: 150,
                   )
                  ),
                  DataColumn(
                  label:Container(
                      child: Text('Image'),
                     // width: 150,
                   )
                  ),
               ],
               rows: posts.map((post) {
                 return DataRow(
                   selected: post.selected,
                   onSelectChanged:(bool value){
                        setState(() {
                          if(post.selected != value){
                            post.selected = value;
                          }
                        });
                   },
                   cells:[
                     DataCell(Text(post.title)),
                     DataCell(Text(post.author)),
                     DataCell(Image.network(post.imageUrl,fit: BoxFit.cover,)),
                 ]);
               }).toList(),
               )
           ],

         )
        ),
    );
  }
  }